<?php
namespace lib\builtin\auth;

trait HasPermissions
{
    /**
     * 给定权限代码
     * 判断是否具有此权限
     *
     * @param string $code 权限代码
     * @throws \lib\builtin\auth\NoPermissionException
     * @return bool 有无权限
     */
    public function can($code)
    {
        /** @var \lib\builtin\auth\Auth $auth */
        $auth = app(Auth::class);
        return $auth->can($this->role, $code);
    }

    /**
     * 要求指定权限
     * 如果没有权限则抛出错误
     *
     * @param string $code 权限代码
     * @throws \lib\builtin\auth\NoPermissionException
     * @return void
     */
    public function needPermission($code)
    {
        /** @var \lib\builtin\auth\Auth $auth */
        $auth = app(Auth::class);
        if (!$auth->can($this->role, $code)) {
            throw new NoPermissionException($auth->findPermission($code));
        }
    }
}
